package com.joysuch.wwyt.common.service.impl;

import com.joysuch.wwyt.common.repository.MailSettingDao;
import com.joysuch.wwyt.common.service.MailSettingService;
import com.joysuch.wwyt.core.bean.MailSettingBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.entity.MailSetting;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author ZhangDong
 * @Date 2020/6/10 11:39
 */
@Service
@Slf4j
public class MailSettingServiceImpl implements MailSettingService {

    @Autowired
    private MailSettingDao mailSettingDao;

    @Override
    @Transactional
    public ResultBean save(MailSettingBean bean) {
        Long id = bean.getId();
        MailSetting mailSetting;
        if (id == null) {
            List<MailSetting> all = mailSettingDao.findAll();
            if (!CollectionUtils.isEmpty(all)) {
                return ResultBean.fail(101, "当前已经配置了邮箱服务器，直接修改即可");
            }
            mailSetting = new MailSetting();
        } else {
            mailSetting = mailSettingDao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
        }
        BeanUtils.copyProperties(bean, mailSetting);
        mailSettingDao.save(mailSetting);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public ResultBean get(Long id) {
        Assert.notNull(id, "id不能为空");
        MailSetting mailSetting = mailSettingDao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
        MailSettingBean mailSettingBean = new MailSettingBean();
        BeanUtils.copyProperties(mailSetting, mailSettingBean);
        return ResultBean.wrapSuccessfulResult(mailSettingBean);
    }

    @Override
    public ResultBean page(Pageable pageable) {
        pageable = PageDataUtils.addOrderByDesc(pageable, "id");
        Page<MailSetting> page = mailSettingDao.findAll(pageable);
        return ResultBean.pageData(page.getContent(), page.getTotalElements());
    }

    @Override
    public ResultBean delete(Long id) {
        Assert.notNull(id, "id不能为空");
        mailSettingDao.deleteById(id);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public MailSetting findOne() {
        List<MailSetting> all = mailSettingDao.findAll();
        if (CollectionUtils.isEmpty(all)) {
            return null;
        }
        return all.get(0);
    }
}
